package com.neuedu.security.controller;

import com.neuedu.security.security.SecurityUserDetails;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
public class UserController {


    /**
     * http://127.0.0.1:8080/index
     * @return
     */
    @RequestMapping("/index")
    String index(){


        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        SecurityUserDetails principal = (SecurityUserDetails) authentication.getPrincipal();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        System.out.println("context.getAuthentication() = " + authentication);
        System.out.println("principal = " + principal);
        System.out.println("authorities = " + authorities);


        return "success";
    }




    /**
     * http://127.0.0.1:8080/root
     * @return
     */
    @Secured({ "ROLE_ADMIN1" })
    @RequestMapping("/root")
    String root(){

        return "root";
    }


    /**
     * http://127.0.0.1:8080/root
     * @return
     */
//    @PreAuthorize("hasRole('admin')")
    @PreAuthorize("hasAuthority('system:user:query')")
    @RequestMapping("/getUserById")
    String getUserById(){

        return "getUserById";
    }


}
